﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxMenu;
using System.Xml;
using SGRapidForm.Common;
using SGRapidForm.Permission.Service.Interface;
using SGRapidForm.Permission.Entity;
using System.Configuration;

namespace SGDemo.Web.UserControls
{
    public partial class Menu : System.Web.UI.UserControl
    {
        /// <summary>
        /// 加载时候绑定控件menuHeader
        /// </summary>
        protected void Page_Load(object sender, EventArgs e)
        {
            menuHeader.DataSourceID = "xdsHeader";
            menuHeader.DataBind();
        }

        private IPermissionService _permissionService = ServiceProxyFactory.Create<IPermissionService>("permissionservice");

        private List<ButtonEntity> _buttons = null;

        private string _pageCode;

        /// <summary>
        /// 当前用户可查看PageCode页的按钮集合
        /// </summary>
        private List<ButtonEntity> Buttons
        {
            get
            {
                if (_buttons != null)
                {
                    return _buttons;
                }
                else
                {
                    _buttons = _permissionService.User_GetButtonBy(ApplicationContext.Current.UserKeyid, this.PageCode);
                    return _buttons;
                }
            }
        }

        /// <summary>
        /// 菜单项绑定事件 - 实现操作菜单权限控制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void menuHeader_ItemDataBound(object sender, MenuItemEventArgs e)
        {
            //是否开启Menu权限控制
            if (ConfigurationManager.AppSettings["EnabledMenuControl"].ToLower().Equals("false")) 
            { 
                return; 
            }

            IHierarchyData itemHierarchyData = (IHierarchyData)e.Item.DataItem;
            XmlElement element = (XmlElement)itemHierarchyData.Item;
            if (element.Attributes["Name"] == null)
            {
                return;
            }

            e.Item.Visible = false;
            foreach (ButtonEntity button in Buttons)
            {
                if (button.ButtonCode == e.Item.Name)
                {
                    e.Item.Visible = true;
                    this.Buttons.Remove(button);
                    return;
                }
            }
        }

        /// <summary>
        /// XML文件
        /// </summary>
        public string DataFile
        {
            set { xdsHeader.DataFile = value; }
        }

        /// <summary>
        /// 页面编码
        /// </summary>
        public string PageCode
        {
            get { return _pageCode; }
            set { _pageCode = value; }
        }
    }
}